package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.home.registered;

import java.util.List;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.UserService;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.UserInfoViewerPanel;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.util.Randomizer;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.util.RandomizerToolbar;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.layout.ColumnLayout;
import com.gwtext.client.widgets.portal.Portlet;

/**
 * @author Renato Miceli
 */
public class RandomRegisteredUsersPortlet extends Portlet implements Randomizer {

	private final InfoManager<UserInfo> loggedManager;

	private static class RandomUserInfoUpdaterCallback implements AsyncCallback<List<UserInfo>> {

		private final UserInfoViewerPanel[] userInfoViewerPanels;

		public RandomUserInfoUpdaterCallback(UserInfoViewerPanel... userInfoViewerPanels) {
			this.userInfoViewerPanels = userInfoViewerPanels;
		}

		/**
		 * {@inheritDoc}
		 */
		public void onFailure(Throwable caught) {
			// Do nothing!
		}

		/**
		 * {@inheritDoc}
		 */
		public void onSuccess(List<UserInfo> result) {
			for (int i = 0; i < userInfoViewerPanels.length; i++) {
				userInfoViewerPanels[i].updateInfo(result.get(i));
			}
		}

	}

	private final UserInfoViewerPanel[] userInfoViewerPanels;

	public RandomRegisteredUsersPortlet(TabPanel centerPanel, InfoManager<UserInfo> loggedManager) {

		this.loggedManager = loggedManager;

		this.setTitle("Random Registered Users");
		this.setLayout(new ColumnLayout());

		this.userInfoViewerPanels = new UserInfoViewerPanel[] { new UserInfoViewerPanel(centerPanel, loggedManager),
				new UserInfoViewerPanel(centerPanel, loggedManager), new UserInfoViewerPanel(centerPanel, loggedManager) };
		for (UserInfoViewerPanel panel : userInfoViewerPanels) {
			this.add(panel);
		}

		this.add(new RandomizerToolbar(this));

		this.randomize();
	}

	/**
	 * {@inheritDoc}
	 */
	public void randomize() {
		final UserInfo info = loggedManager.getInfo();
		UserService.Util.getInstance().getRandomUserInfos(info.getLogin(), info.getPassword(), this.userInfoViewerPanels.length,
				new RandomUserInfoUpdaterCallback(userInfoViewerPanels));
	}

}
